package com.wk.data.cahce;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;


/**
 * 最近最少使用 淘汰策略LRU
 * 
 * LFU
 */
public class LRU {
	 private final ReentrantLock lock = new ReentrantLock();

	    private final Map<String, String> map = new ConcurrentHashMap<String, String>();
	    private final Deque<String> queue = new LinkedList<String>();
	    private final int limit;

	    public LRU(int limit) {
	        this.limit = limit;
	    }

	    public void put(String key, String value) {
	        String oldValue = map.put(key, value);
	        if (oldValue != null) {
	            removeThenAddKey(key);
	        } else {
	            addKey(key);
	        }
	        if (map.size() > limit) {
	            map.remove(removeLast());
	        }
	    }

	    public String get(String key) {
	        String String = map.get(key);
	        if(String != null){
	            removeThenAddKey(key);
	        }
	        return String;
	    }

	    private void addKey(String key) {
	        lock.lock();
	        try {
	            queue.addFirst(key);
	        } finally {
	            lock.unlock();
	        }
	    }

	    private String removeLast() {
	        lock.lock();
	        try {
	            final String removedKey = queue.removeLast();
	            return removedKey;
	        } finally {
	            lock.unlock();
	        }
	    }

	    private void removeThenAddKey(String key) {
	        lock.lock();
	        try {
	            queue.removeFirstOccurrence(key);
	            queue.addFirst(key);
	        } finally {
	            lock.unlock();
	        }

	    }

	    private void removeFirstOccurrence(String key) {
	        lock.lock();
	        try {
	            queue.removeFirstOccurrence(key);
	        } finally {
	            lock.unlock();
	        }
	    }

	    public String getSilent(String key) {
	        return map.get(key);
	    }

	    public void remove(String key) {
	        removeFirstOccurrence(key);
	        map.remove(key);
	    }

	    public int size() {
	        return map.size();
	    }

	    public String toString() {
	        return map.toString();
	    }
}
